<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>加密货币价格监控</title>
    <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f9f9f9;
        }
        h1 {
            text-align: center;
            color: #333;
        }
        .price-container {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            justify-content: flex-start;
        }
        .price-card {
            background: white;
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 15px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            width: calc(50% - 30px); /* 两列布局，减去间距 */
            box-sizing: border-box;
            font-size: 14px;
        }
        .price-up {
            color: green;
        }
        .price-down {
            color: red;
        }
        @media (min-width: 1200px) {
            .price-card {
                display: block;
            }
        }
        #connectionStatus {
            position: sticky;
            top: 0;
            background: rgba(255, 255, 255, 0.9);
            z-index: 100;
            padding: 5px;
        }

        @media (max-width: 768px) {
            .price-card {
                width: 100%; /* 在移动端使用单列布局 */
            }
            body {
                padding: 10px;
            }
        }
    </style>
</head>
<body>
<h1>实时价格监控</h1>
<div id="priceTable" class="price-container"></div>

<!-- 返回首页按钮 -->
<div class="fixed bottom-0 left-0 right-0 bg-white shadow-lg p-2 flex justify-center">
    <a href="/" class="text-blue-600 hover:text-blue-800">返回首页</a>
</div>

<script>
    const mqttConfig = {
        host: '192.168.0.200',
        port: 8083,
        wsPort: 8083,
        wssPort: 8083,
        username: 'trace_rule_client',
        password: 'trace_rule_client'
    };

    // 添加连接状态显示
    function updateConnectionStatus(status, error = '') {
        const statusHtml = `
            <div style="text-align: center; margin: 10px; padding: 10px;
                        ${status === 'connected' ? 'color: green;' : 'color: red;'}">
                ${status === 'connected' ? '已连接' : '连接断开'} ${error}
            </div>`;
        document.getElementById('connectionStatus').innerHTML = statusHtml;
    }

    // 在 priceTable 之前添加状态显示区域
    const statusDiv = document.createElement('div');
    statusDiv.id = 'connectionStatus';
    document.getElementById('priceTable').parentNode.insertBefore(statusDiv, document.getElementById('priceTable'));

    let connectAttempts = 0;
    const maxAttempts = 3;

    function connectMQTT() {
        try {
            // 首先尝试 ws 连接
            const client = mqtt.connect(`ws://${mqttConfig.host}:${mqttConfig.wsPort}/mqtt`, {
                username: mqttConfig.username,
                password: mqttConfig.password,
                reconnectPeriod: 1000,
                connectTimeout: 5000,
            });

            client.on('connect', function() {
                console.log('Connected to MQTT broker');
                updateConnectionStatus('connected');
                client.subscribe('/sys/crypto/price');
                connectAttempts = 0;
            });

            client.on('error', function(error) {
                console.error('Connection error:', error);
                updateConnectionStatus('disconnected', '- 连接错误');
            });

            client.on('offline', function() {
                console.log('Client is offline');
                updateConnectionStatus('disconnected', '- 离线');
            });

            client.on('message', function(topic, message) {
                const data = JSON.parse(message.toString());
                let html = '';

                data.forEach(item => {
                    const priceChangeClass = parseFloat(item.priceChange) >= 0 ? 'price-up' : 'price-down';
                    html += `
                        <div class="price-card">
                            <div><strong>交易对:</strong> ${item.symbol}</div>
                            <div><strong>最新价格:</strong> ${item.lastPrice}</div>
                            <div class="${priceChangeClass}"><strong>价格变化:</strong> ${item.priceChange}</div>
                            <div class="${priceChangeClass}"><strong>涨跌幅:</strong> ${item.priceChangePercent}%</div>
                            <div><strong>24h最高:</strong> ${item.highPrice}</div>
                            <div><strong>24h最低:</strong> ${item.lowPrice}</div>
                            <div><strong>成交量:</strong> ${item.volume}</div>
                            <div><strong>成交额:</strong> ${item.quoteVolume}</div>
                            <div><strong>开盘时间:</strong> ${formatTime(item.openTime)}</div>
                            <div><strong>收盘时间:</strong> ${formatTime(item.closeTime)}</div>
                        </div>
                    `;
                });

                document.getElementById('priceTable').innerHTML = html;
            });

            return client;
        } catch (error) {
            console.error('MQTT connection error:', error);
            updateConnectionStatus('disconnected', '- 连接失败');

            if (connectAttempts < maxAttempts) {
                connectAttempts++;
                setTimeout(connectMQTT, 2000); // 2秒后重试
            }
        }
    }

    const client = connectMQTT();

    function formatTime(timestamp) {
        return new Date(timestamp).toLocaleString('zh-CN');
    }
</script>
</body>
</html>
